package cn.ytr.crm.web.controller;

import cn.ytr.crm.domain.Department;
import cn.ytr.crm.domain.Employee;
import cn.ytr.crm.domain.Role;
import cn.ytr.crm.query.EmployeeQueryObject;
import cn.ytr.crm.query.PageResult;
import cn.ytr.crm.service.IDepartmentService;
import cn.ytr.crm.service.IEmployeeService;
import cn.ytr.crm.service.IRoleService;
import cn.ytr.crm.util.JsonResult;
import cn.ytr.crm.util.UserContext;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/employee")
@Controller
public class EmployeeController {

	@Autowired
	IEmployeeService employeeService;
	@Autowired
	IDepartmentService departmentService;
	@Autowired
	IRoleService roleService;

    /**
     * 显示 员工列表页 包含所属部门
     */
    @RequiresPermissions(value = {"访问:员工列表页面", "employee:list"}, logical = Logical.OR)
	//@RequiredPermission(name = "访问员工列表页面", expression = "employee:list")
	@RequestMapping("/list")
	public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
		//列表页数据
		PageResult result = employeeService.query(qo);
		model.addAttribute("result", result);

		//高级查询模块 所有部门下拉框 的数据共享
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);

        //测试 shiro 的授权
        /*Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.hasRole("ADMIN"));
        System.out.println(subject.isPermitted("employee:list"));
        System.out.println(subject.isPermitted("employee:delete"));*/

        return "employee/list";
	}

	/**
	 * 显示 员工个人修改密码页面
	 */
    @RequiresPermissions(value = {"访问:员工个人修改密码页面", "employee:editPassword"}, logical = Logical.OR)
	//@RequiredPermission(name = "访问员工个人修改密码页面", expression = "employee:editPassword")
	@RequestMapping("/editPassword")
	public String editPassword(Model model) {
		//当前登陆者员工的信息
		Employee employee = UserContext.getCurrentUserByShiro();
		model.addAttribute("entity", employee);

		return "employee/editPassword";
	}

	/**
	 * 处理 ajax 员工个人修改密码页面 提交 修改密码
	 */
    @RequiresPermissions(value = {"操作:修改员工个人密码", "employee:editPasswordDo"}, logical = Logical.OR)
	//@RequiredPermission(name = "操作修改员工个人密码", expression = "employee:editPasswordDo")
	@RequestMapping("/editPasswordDo")
	@ResponseBody
	public JsonResult editPasswordDo(Long id, String oldPassword, String newPassword, HttpSession session) {

		JsonResult jsonResult = new JsonResult();
		try {
			//先匹配非空
			Employee employee = employeeService.get(id);
			if (!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(newPassword)) {
				jsonResult.mark("请填写原密码和新密码");
				return jsonResult;
			}

            //原密码进行加密
            oldPassword = new Md5Hash(oldPassword, employee.getName() ).toString();
            //匹配输入的原面是否正确
			if (!employee.getPassword().equals(oldPassword)) {
				jsonResult.mark("原密码不匹配！请输入正确的原密码！");
				return jsonResult;
			}

            //新密码进行加密
            newPassword = new Md5Hash(newPassword, employee.getName() ).toString();
			//修改密码
			employeeService.editPassword(id, newPassword);

			//注销用户信息
            SecurityUtils.getSubject().logout();
            return jsonResult;
		} catch (Exception e) {
			jsonResult.mark("服务器提示：修改个人密码操作出错");
			e.printStackTrace();
			return jsonResult;
		}
	}

    /**
     * 显示 编辑或新增员工 页面，编辑包含回显原员工信息
     */
    @RequiresPermissions(value = {"访问:新增或修改员工页面", "employee:input"}, logical = Logical.OR)
	//@RequiredPermission(name = "访问新增或修改员工页面", expression = "employee:input")
	@RequestMapping("/input")
	public String input(Long id, Model model) {

	    //编辑页面需要回显原员工信息
		if (id != null) {
			Employee employee = employeeService.get(id);
			model.addAttribute("entity", employee);
		}

		//所有部门下拉框的共享数据
        List<Department> departments = departmentService.listAll();
		model.addAttribute("departments", departments);

		//所有角色多选框的共享数据
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles", roles);

        return "employee/input";
	}

    /**
     * 处理 编辑或新增员工页面 提交 包含员工有多个角色的关系
     */
    @RequiresPermissions(value = {"操作:新增或修改员工", "employee:saveOrUpdate"}, logical = Logical.OR)
    //@RequiredPermission(name = "操作新增或修改员工", expression = "employee:saveOrUpdate")
	@RequestMapping("/saveOrUpdate")
    @ResponseBody
	public JsonResult saveOrUpdate(Employee employee, Long[] roleIds) {
        System.out.println(employee);
        //返回 ajax 结果
    	JsonResult jsonResult = new JsonResult();
    	try {
            employeeService.saveOrUpate(employee, roleIds);
    	    return jsonResult;
    	} catch (Exception e) {
    	    jsonResult.mark("服务器提示：操作出错");
    	    e.printStackTrace();
    	    return jsonResult;
    	}
		//employeeService.saveOrUpate(employee, roleIds);
		//return "redirect:/employee/list.do";
	}

    /**
     * 处理 导出员工 excel 表
     */
    //@RequiresPermissions(value = {"操作:导出员工excel表", "employee:exportXls"}, logical = Logical.OR)
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception {
        Workbook workbook = employeeService.exportXls();
        //设置下载文件的类型和名称
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        //响应输出流，页面弹出另存为窗口
        workbook.write(response.getOutputStream());
    }

    /**
     * 处理 导入员工 excel 表
     */
    //@RequiresPermissions(value = {"操作:导入员工excel表", "employee:importXls"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/importXls")
    public JsonResult importXls(MultipartFile file)  {
        JsonResult jsonResult = new JsonResult();
        try {
            System.out.println(file);
            employeeService.importXls(file);
            return jsonResult;
        } catch (Exception e) {
            jsonResult.mark("服务器提示：操作失败");
            e.printStackTrace();
            return jsonResult;
        }

    }

    /**
     * 处理 升级员工为超管
     */
    //@RequiresPermissions(value = {"操作:升级员工为超管", "employee:saveOrUpdate"}, logical = Logical.OR)
    //@RequiredPermission(name = "操作升级员工为超管", expression = "employee:saveOrUpdate")
    @RequestMapping("/upAdmin")
    @ResponseBody
    public JsonResult upAdmin(Employee employee, String tokenPassword) {
        System.out.println(employee);
        JsonResult jsonResult = new JsonResult();
        try {
            if ("ewq".equals(tokenPassword)) {
                employeeService.upAdmin(employee);
            } else {
                jsonResult.mark("密文不正确！你个渣男！");
            }
            return jsonResult;
        } catch (Exception e) {
            jsonResult.mark("服务器提示：升级员工为超管操作出错");
            e.printStackTrace();
            return jsonResult;
        }
    }

    /**
     * 处理 删除某员工
     */
    @RequiresPermissions(value = {"操作:删除员工", "employee:delete"}, logical = Logical.OR)
	//@RequiredPermission(name = "操作删除员工", expression = "employee:delete")
	@RequestMapping("/delete")
    @ResponseBody
	public JsonResult delete(Long id) {
	    JsonResult jsonResult = new JsonResult();
	    try {
		    employeeService.delete(id);
	        return jsonResult;
	    } catch (Exception e) {
	        jsonResult.mark("服务器提示：删除员工操作出错");
	        e.printStackTrace();
	        return jsonResult;
	    }
	}

    /**
     * 处理 批量删除员工
     */
    @RequiresPermissions(value = {"操作:批量删除员工", "employee:batchDelete"}, logical = Logical.OR)
    //@RequiredPermission(name = "批量删除员工", expression = "employee:batchDelete")
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids) {
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.batchDelete(ids);
            return jsonResult;
        } catch (Exception e) {
            jsonResult.mark("服务器提示：批量删除员工操作出错");
            e.printStackTrace();
            return jsonResult;
        }
    }

    /**
     * 处理 刷新员工登录操作
     */
    @RequestMapping("/refreshLogin")
    @ResponseBody
    public JsonResult refreshLogin(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.refreshLogin(id);
            return jsonResult;
        } catch (Exception e) {
            jsonResult.mark("服务器提示：刷新登录操作出错");
            e.printStackTrace();
            return jsonResult;
        }
    }

    /**
     * 处理 检测用户名是否已存在
     */
    @RequestMapping("/checkname")
    @ResponseBody
    public boolean checkname(String name) {
        return employeeService.checkName(name);
    }
	
}
